/**
 * Created by waterworld on 17-7-22.
 */
var config=require('./../config/config');
var iconst=require('./iconst');
var P = require("bluebird");
var Token=require('./../token');
var room=require('./room_d89');
var trobot=require('./robot');
var http = require('http');
var robot=new trobot();
var userDao;
var redis;
var redis=new predis(1234);
var roomManage=function(redis0,userDao0)
{
    this.redis=redis0;
    this.userDao=userDao0;
    redis=redis0;
    userDao=userDao0;
    this.socketMap={};
    this.socketInfo={};
    this.uidMap={};
    this.uidSocketMap={};
    this.roomList=[];
    this.uidStatusMap={};
    this.roomMap={};
    for(var i=0;i<iconst.maxRoom;i++)
    {   var rm=new room(i,this);
        this.roomList.push(rm);
    }
    setInterval(this.onUpdate.bind(this),500);
};


roomManage.prototype.getAliveUserCount=function()
{
    var count=0;
    for(var i=0;i<iconst.maxRoom;i++)
    {
        var rm=this.roomList[i];
        count+=rm.getUserCount();
    }
    return count;
};

roomManage.prototype.reloadFromRedis= P.coroutine(function*()
{
    var t1=new Date().getTime();
    console.logg('开始加载缓存信息 ');
    for(var i=0;i<iconst.maxRoom;i++)
    {
        var roomInfo=yield this.redis.getHashItem('d89_roomMap',i);
        if(roomInfo)
        {   var info=JSON.parse(roomInfo);
            //var rid=this.roomList[i].createRoomByRedis(info.owner,info,info.roomPsw);
            //console.log('游戏重启中，从缓存加载房间信息',roomInfo);
            yield this.clearRedisRoom(i,info);
        }
    }
    var t2=(new Date().getTime()-t1)/1000;
    console.logg('加载缓存信息耗时 ',t2);
});

roomManage.prototype.clearRedisRoom= P.coroutine(function*(rid,roomInfo)
{
    console.logg('清理房间信息',rid,roomInfo);
    yield this.redis.delHashItem('d89_roomMap',rid);
    yield this.redis.delHashItem(iconst.gameHistoryName,'room_'+roomInfo.roomPsw);
});

roomManage.prototype.recordRoom2Redis= P.coroutine(function*(rid,roomInfo)
{
    console.logg('记录房间信息',rid,roomInfo);
    yield this.redis.setHashItem('d89_roomMap',rid,roomInfo);

});


roomManage.prototype.bindSocket=function(uid,socket)
{
    this.uidSocketMap[uid]=socket;
    socket.uid=uid;
};

roomManage.prototype.bindRoomSocket=function(roomId,uid)
{
    var suid=roomId+uid;
    this.uidSocketMap[suid]=this.uidSocketMap[uid];

};

roomManage.prototype.unbindSocket=function(socket)
{
    var uid=socket.uid;
    if(!uid) return;
    delete this.uidSocketMap[uid];
   console.log('delete uid socket ++++',uid);
};

roomManage.prototype.unbindRoomSocket=function(roomId,uid)
{
    var suid=roomId+uid;
    this.uidSocketMap[suid]=null;
};


roomManage.prototype.clientConnect=function(socket)
{   var id=socket.conn.id;
    this.socketMap[id]=socket;
};

roomManage.prototype.clientDisconnect=function(socket)
{
    var uid=socket.uid;
    this.delUserStatus(uid);

    var rm=this.getUserRoom(uid);
    if(rm)
    {rm.exitRoom(uid); }//玩家掉线了要通知别的玩家状态变化
    else{console.logg('clientDisconnect invalid room ',uid,socket.conn.id);}
    this.unbindSocket(socket);
};
roomManage.prototype.forceKick=function(uid)
{
    console.logg('force kick ',uid);
    if(!this.uidSocketMap) this.uidSocketMap={};
    var oldSocket=this.uidSocketMap[uid];
    if(!oldSocket) return;
    console.logg('强制关闭玩家连接',oldSocket.conn.id);
    oldSocket.disconnect();
    if(oldSocket.clear)  oldSocket.clear();
    delete this.uidSocketMap[uid];
}

roomManage.prototype.kick=function(uid,socket)
{
    console.logg('kick ',uid);
    if(!this.uidSocketMap) this.uidSocketMap={};
    var oldSocket=this.uidSocketMap[uid];
    if(!oldSocket) return;
    if(oldSocket.conn.id!=socket.conn.id)
    {   console.logg('相同的玩家进入同一个游戏，踢掉之前的连接',oldSocket.conn.id);
        oldSocket.disconnect();
        delete this.uidSocketMap[uid];
        this.uidSocketMap[uid]=socket;
        socket.uid=uid;
    }
}
roomManage.prototype.getUserInfo=function(uid)
{
    var  userInfo=this.uidMap[uid];
    return userInfo;
}

roomManage.prototype.setUserInfo=function(uid,info)
{
    this.uidMap[uid]=info;
}

roomManage.prototype.setUserStatus=function(uid,status)
{    this.uidStatusMap[uid]=status;
}

roomManage.prototype.getUserStatus=function(uid)
{    return this.uidStatusMap[uid];
}

roomManage.prototype.delUserStatus=function(uid)
{    delete this.uidStatusMap[uid];
}


roomManage.prototype.setUserRoom=function(uid,rid)
{
    var  userInfo=this.uidMap[uid];
    if(!userInfo)
    { return null;}
    var  rm=this.roomList[rid];
    console.logg('roomManage setUserRoom ',uid,rid);
    if(rm) userInfo.roomIndex=rid;
}
roomManage.prototype.getUserRoom=function(uid)
{
    var  userInfo=this.uidMap[uid];
    if(!userInfo)
    { return null;}
    var roomIndex=userInfo.roomIndex;
    var  rm=this.roomList[roomIndex];
    if(!rm)
    { this.sendByUid(uid,{event:iconst.event.error,msg:'invalidRoom'}); }
    return rm;
}
roomManage.prototype.clearUserRoom=function(uid)
{
    var  userInfo=this.uidMap[uid];
    if(!userInfo)
    { return null;}
    userInfo.roomIndex=-1;
}

roomManage.prototype.clearUserInfo=function(uid)
{
    delete this.uidMap[uid];
}
roomManage.prototype.sysCreateRoom0= P.coroutine(function*(socket,data)
{
        var uid=-1;
    var  token=data.token;
    var  createData=data;
        try
        {   uid=Token.aesDecodeDef(token);
        }
        catch(e)
        {    console.logg('解析token信息失败');
            var  msg={code:500,msg:'解析token信息失败'};
            var  s=JSON.stringify(msg);
            socket.emit('sys',s);
            setTimeout(function()
            {socket.disconnect();
            },
            100);
            return;
        }
    var historyName=iconst.gameHistoryName;
    var  key='user_'+uid;
    var  self=this;
    var  roomId=yield self.redis.getHashItem(historyName,key);
    console.logg('get history user_uid',key,roomId);
    var roomData=null;
    var  roomData=null;
    if(roomId)
    {
        console.logg('历史房间号',roomId);
        var offlineData=yield self.redis.getHashItem(historyName,roomId);
        console.logg(roomId,'历史房间信息',offlineData);
        if(!offlineData)
        {
        }
        else
        {
            try{roomData=JSON.parse(offlineData);}
            catch(e)
            { roomData=null;
            }
            if(roomData&&roomData.gameType=='d89')
            {   roomData.code=200;
                var s=JSON.stringify(roomData);
                console.logg('sysCreateRoom get History info',s);
                socket.emit('sys',s);
                setTimeout(function(){socket.disconnect();},
                    100);
                return roomData;
            }

        }
    }
    var userInfo=yield self.getDbUserInfo(uid);
    if(userInfo==null)
    {  console.logg('读取用户信息失败');
        socket.emit('sys','读取用户信息失败');
        setTimeout(function(){socket.disconnect();},
            100);
        self.sendMsg(socket,{event:iconst.event.error,msg:'get userInfo failed'});
        self.setUserStatus(uid,iconst.userStatus.onIdle);
        return;}

    self.setUserInfo(uid,userInfo);
    console.logg('login Info ',userInfo.uid,userInfo.name,userInfo.cardNum);
    var isAgent= Array.from(userInfo.isAgent);
    var yesno=0;
    if(isAgent[0]==1){ yesno=1;}
    console.logg('login finished',userInfo);
    var msg={event:iconst.event.login,uid:userInfo.uid,token:token,name:userInfo.name,cardNum:userInfo.cardNum,
        imgurl:userInfo.headimgurl,cdnImgurl:userInfo.cdnImgurl,
        inviteInfo:userInfo.code,ip:createData.ip,isAgent:yesno};
    //来到这里就需要创建一个新房间了
    for(var i=0;i<3;i++)
    {   randomId=self.random(100000,999999);
        roomInfo=yield redis.getHashItem(iconst.gameHistoryName,'room_'+randomId);
        if(roomInfo==null)
        {  break; }
    }
    if(roomInfo!=null)
    {
        console.logg('玩家',uid,'创建房间失败');
        var s=JSON.stringify({code:500,msg:"创建房间失败"});
        socket.emit('sys',s);
        setTimeout(function(){socket.disconnect();},
            100);
        return null;
    }
    var len=self.roomList.length;
    for(var i=0;i<len;i++)
    {
        var rm=self.roomList[i];
        var n=rm.getUserCount();
        if(n==0)
        {
            console.logg('尝试创建房间');
            var rid=yield rm.createRoomSync(uid,createData,randomId);
            if(rid>=0)
            {   var userInfo=self.getUserInfo(uid);
                self.setUserRoom(uid,rid);
                var n=new Date().getTime();
                rm.set('createTick',n);
                roomInfo={owner:uid,rid:rid,roomId:randomId,roomPsw:randomId,tick:n,gameType:'d89',gameCount:rm.get('gameCount'),
                name:userInfo.name,headimgurl:userInfo.headimgurl,gameStatus:'create',
                    serverName:self.serverName,
                    innerGameType:createData.gameType,diFeng:createData.diFeng};
                var s=JSON.stringify(roomInfo);
                console.logg('玩家',uid,"创建房间",randomId,s);
                yield self.recordRoom2Redis(rid,s);
                yield redis.setHashItem('d89_roomMap','r'+randomId,s);
                yield redis.setHashItem(iconst.gameHistoryName,'room_'+randomId,s);
                roomInfo.code=200;
                var s=JSON.stringify(roomInfo);
                socket.emit('sys',s);
                setTimeout(function(){socket.disconnect();},
                    100);
                return;
            }
            else
            {
                if(rid==-1)
                    console.logg('玩家创建房间失败，没有足够的房卡');
                var  s=JSON.stringify({code:500,msg:"no card"});
                socket.emit('sys',s);
                setTimeout(function(){socket.disconnect();},
                    100);
                return;
            }
        }
    }
    var s=JSON.stringify({code:500,msg:"failed end"});
    socket.emit('sys',s);
    setTimeout(function(){socket.disconnect();},
        100);
});



roomManage.prototype.sysCreateRoom= P.coroutine(function*(socket,data)
{
    var uid=-1;
    var  token=data.token;
    var  createData=data;
    try
    {   uid=Token.aesDecodeDef(token);
    }
    catch(e)
    {    console.logg('解析token信息失败');
        var  msg={code:500,msg:'解析token信息失败'};
        var  s=JSON.stringify(msg);
        socket.emit('sys',s);
        setTimeout(function()
            {socket.disconnect();
            },
            100);
        return;
    }
    var historyName=iconst.gameHistoryName;
    var  key='user_'+uid;
    var  self=this;

    var userInfo=yield self.getDbUserInfo(uid);
    if(userInfo==null)
    {  console.logg('读取用户信息失败');
        socket.emit('sys','读取用户信息失败');
        setTimeout(function(){socket.disconnect();},
            100);
        self.sendMsg(socket,{event:iconst.event.error,msg:'get userInfo failed'});
        self.setUserStatus(uid,iconst.userStatus.onIdle);
        return;}

    self.setUserInfo(uid,userInfo);
    console.logg('login Info ',userInfo.uid,userInfo.name,userInfo.cardNum);
    var isAgent= Array.from(userInfo.isAgent);
    var yesno=0;
    if(isAgent[0]==1){ yesno=1;}
    console.logg('login finished',userInfo);
    var msg={event:iconst.event.login,uid:userInfo.uid,token:token,name:userInfo.name,cardNum:userInfo.cardNum,
        imgurl:userInfo.headimgurl,cdnImgurl:userInfo.cdnImgurl,
        inviteInfo:userInfo.code,ip:createData.ip,isAgent:yesno};
    //来到这里就需要创建一个新房间了
    var  roomInfo=null;
    for(var i=0;i<3;i++)
    {   randomId=self.random(100000,999999);
        roomInfo=yield redis.getHashItem(iconst.gameHistoryName,'room_'+randomId);
        if(roomInfo==null)
        {  break; }
    }
    if(roomInfo!=null)
    {
        console.logg('玩家',uid,'创建房间失败');
        var s=JSON.stringify({code:500,msg:"创建房间失败"});
        socket.emit('sys',s);
        setTimeout(function(){socket.disconnect();},
            100);
        return null;
    }
    var len=self.roomList.length;
    for(var i=0;i<len;i++)
    {
        var rm=self.roomList[i];
        var n=rm.getUserCount();
        if(n==0)
        {
            console.logg('尝试创建房间');
            var rid=yield rm.createRoomSync(uid,createData,randomId);
            if(rid>=0)
            {   var userInfo=self.getUserInfo(uid);
                var  gamingRoomInfo=yield self.getPlayerGamingRoom(uid);
                userInfo.gamingRoomInfo=gamingRoomInfo;
                self.setUserRoom(uid,rid);
                var n=new Date().getTime();
                rm.set('createTick',n);
                var  url='H5_d89?roomId='+randomId+'&tick='+n;
                console.logg('createRoom url='+url);
                var  data={};
                roomInfo={owner:uid,rid:rid,roomId:randomId,roomPsw:randomId,tick:n,gameType:'d89',gameCount:rm.get('gameCount'),
                    name:userInfo.name,headimgurl:userInfo.headimgurl,gameStatus:'create',
                    serverName:self.serverName,
                    innerGameType:createData.gameType,diFeng:createData.diFeng};
                data.diFen=rm.get('diFeng');data.gameCount=rm.get('gameCount');
                roomInfo.createData=data;
                var s=JSON.stringify(roomInfo);
                console.logg('玩家',uid,"创建房间",randomId,s);
                yield self.recordRoom2Redis(rid,s);
                yield redis.setHashItem('d89_roomMap','r'+randomId,s);
                yield redis.setHashItem(iconst.gameHistoryName,'room_'+randomId,s);
                roomInfo.code=200;
                var s=JSON.stringify(roomInfo);
                socket.emit('sys',s);
                setTimeout(function(){socket.disconnect();},
                    200);
                return;
            }
            else
            {
                var  s=JSON.stringify({code:500,msg:"no card"});
                if(rid==-1)
                    console.logg('玩家创建房间失败，没有足够的房卡');
                if(rid==-2)
                {
                    s=JSON.stringify({code:500,msg:"已开始固定庄家模式不能再创建房间"});
                    console.logg(s);
                }
                socket.emit('sys',s);
                setTimeout(function(){socket.disconnect();},
                    200);
                return;

            }

        }
    }
    var s=JSON.stringify({code:500,msg:"failed end"});
    socket.emit('sys',s);
    setTimeout(function(){socket.disconnect();},
        100);
});

roomManage.prototype.userLogin=function(socket,data)
{
    var self=this;
    var userInfo=null;

    if(typeof data=='string')
    {   console.logg('try parse ',data);
        try
        { data=JSON.parse(data);}
        catch(e)
        { console.logg('parse data exception ',data);
        }
    }
    var token=data.token;
    var stoken=data.stoken;
    if(!token||!stoken)
    {
        console.logg('invalid token stoken',token,stoken);
        this.sendMsg(socket,{event:iconst.event.error,msg:'无效的参数'});
        return; }
    var uid,ip;
    try
    {   uid=Token.aesDecodeDef(token);
        ip=Token.aesDecodeDef(stoken);
    }
    catch(e)
    {    console.logg('解析token信息失败');
        this.sendMsg(socket,{event:iconst.event.error,msg:'parse token failed'});
        return;
    }
    this.kick(uid,socket);
    this.bindSocket(uid,socket);
    var status=this.getUserStatus(uid);
    if(status!=undefined&&status!=iconst.userStatus.onIdle)
    {   console.logg('正在登录中,不能反复登录....',uid);
        return;
    }
    this.setUserStatus(uid,iconst.userStatus.login);
    var doAsync= P.coroutine(function*(data)
    {
        var userInfo=yield self.getDbUserInfo(uid);
        if(userInfo==null)
        {  console.logg('读取用户信息失败');
            self.sendMsg(socket,{event:iconst.event.error,msg:'get userInfo failed'});
            self.setUserStatus(uid,iconst.userStatus.onIdle);
            return;}
        userInfo.ip=ip;
        self.setUserInfo(uid,userInfo);
        console.logg('login Info ',userInfo.uid,userInfo.name,userInfo.cardNum);
        var isAgent= Array.from(userInfo.isAgent);
        var yesno=0;
        if(isAgent[0]==1){ yesno=1;}
        var  enter=yield self.tryEnterRoomByHistory(uid);
        if(enter==0)
        {
            console.logg('进入房间失败');
        }
        console.logg('login finished',userInfo);
        self.sendMsg(socket,{event:iconst.event.login,uid:userInfo.uid,token:token,name:userInfo.name,cardNum:userInfo.cardNum,
            imgurl:userInfo.headimgurl,cdnImgurl:userInfo.cdnImgurl,
            inviteInfo:userInfo.code,ip:ip,isAgent:yesno});
        self.setUserStatus(uid,iconst.userStatus.onIdle);
        if(enter==iconst.loginByHistory)
        {   self.setUserStatus(uid,iconst.userStatus.onIdle);
            return;
        }
        var  createData=data.createData;
        if(createData!=undefined)
        { self.playerCreateRoom(userInfo.uid,createData);}
        var  enterData=data.enterData;
        if(enterData!=undefined)
        { self.playerEnterRoom(userInfo.uid,enterData);}

    });
    doAsync(data).catch(function(e)
    {  self.setUserStatus(uid,iconst.userStatus.onIdle);
       console.logg('user login exception', e.message);
    });
};

roomManage.prototype.getDbUserInfo= P.coroutine(function*(uid)
{
    var record=yield userDao.getUserByIdAsync(uid);
    if(record==null) return null;
    return record;
});

/*
roomInfo
{
 "100113": "100113",
 "100114": "100114",
 "100116": "100116",
 "roomId": 838524,
 "gaming": true,
 "gameType": "zjh"
 }
 */
roomManage.prototype.checkAndCreateRoom= P.coroutine(function*(roomInfo)
{
    if(roomInfo.serverName!=this.serverName)
    {   console.logg('checkAndCreateRoom 房间名不匹配',roomInfo.serverName,this.serverName);
        return;
    }
    var  roomIndex=roomInfo.rid;
    var  room=this.roomList[roomIndex];
    var  roomPsw=room.get("roomPsw");
    if(roomPsw==null||roomPsw==undefined)
    {
        console.logg('房间为空的重新创建',this.serverName);
        this.playerCreateRoom(roomInfo.owner,roomInfo);
    }
});

roomManage.prototype.tryEnterRoomByHistory= P.coroutine(function*(uid)
{
    return 0;
    var self=this;
    var historyName=iconst.gameHistoryName;
    var  key='user_'+uid;
    var  roomId=yield self.redis.getHashItem(historyName,key);
    console.logg('get history user_uid',key,roomId);
    var roomData=null;
    if(roomId)
    {
        console.logg('历史房间号',roomId);
        var offlineData=yield self.redis.getHashItem(historyName,roomId);
        console.logg(roomId,'历史房间信息',offlineData);
        if(!offlineData||offlineData==null||offlineData=='null')
        {   console.logg(roomId,'没有历史房间信息',offlineData);
            return 0;
        }
        else
        {   try{roomData=JSON.parse(offlineData);}
            catch(e)
            { roomData=null;}
            if(roomData&&roomData.gameType=='d89')
            {
                console.logg('已经在房间中，重新进入 ',uid,roomData.roomPsw);
                var rid=roomData.rid;
                var rm=self.roomList[rid];
                if(rm)
                {
                    var n=rm.getUserCount();
                    var  psw=rm.getRoomPsw();
                    if(psw==null)
                    {   console.logg('房间完全为空');
                        if(self.serverName==roomData.serverName)
                        {
                            console.logg('房间完全为空，重新恢复房间',roomData.rid,roomData.roomPsw);
                            var rm=self.roomList[roomData.rid];
                            var rid=rm.createRoom(roomData.owner,roomData,roomData.roomPsw);
                            self.setUserRoom(roomData.owner,roomData.rid);
                            rm.set('createTick',roomData.tick);
                        }
                        else
                        { return 0;
                        }
                        //yield self.redis.delHashItem(historyName,key);
                        //yield self.redis.delHashItem(historyName,roomId);
                        //self.sendByUid(uid,{event:iconst.event.error,msg:"房间不存在"});

                    }
                    var  rm1=self.getUserRoom(uid);
                    if(rm1)
                    {   console.logg('已经在房间中了++++ ',rm1.roomPsw,roomData.roomPsw);
                        rm1.notifyUpdate();
                        return iconst.loginByHistory;
                    }
                    var ret=rm.enterRoom(uid,roomData.roomPsw);
                    if(ret==true)
                    { self.setUserRoom(uid,rm.roomId);
                        return iconst.loginByHistory;
                    }
                    return 0;
                }
                else
                {
                    console.logg('can not find room ',uid,roomId);
                }
                return 0;
            }
            else
            {
                console.logg('已在别的游戏中');
                self.sendByUid(uid,{event:iconst.event.error,msg:"已在别的游戏中"});
                return iconst.inOtherGame;
            }
        }
    }
    return 0;
});


roomManage.prototype.sendMsg=function(socket,data)
{
    socket.emit('onGame',data);
};


roomManage.prototype.sendByUid=function(uid,data)
{
    var socket=this.uidSocketMap[uid];
    if(socket)
    {   this.sendMsg(socket,data);
        return;
    }
    //console.logg('no socket bind with ',uid);
};

roomManage.prototype.sendByRoom=function(roomId,uid,data)
{
    var  suid=roomId+uid;
    var socket=this.uidSocketMap[suid];
    if(socket)
    {   this.sendMsg(socket,data);
        return;
    }
    //console.logg('no socket bind with ',uid);
};

roomManage.prototype.playerOpt=function(socket,data)
{
    var uid=socket.uid;
    var  userInfo=this.getUserInfo(uid);
    if(userInfo)
    { userInfo.liveTick=new Date().getTime();
    }
    if(uid==undefined||uid==-1)
    {  return;}
    var event=data.event;
    if(event==iconst.event.keepAlive)
    {this.sendMsg(socket,data)//keepAlive 原样返回实现心跳机制
    //return;
    }
    else
    {
        console.logg('playOpt event',event);
    }
    var status=this.getUserStatus(uid);
    if(status!=iconst.userStatus.onIdle)
    { console.logg('正在进行耗时操作,不能进行下一步....',status);
      return;
    }
    this.playerKeepAlive(uid);
    if(event==iconst.event.createRoom)
    {   this.playerCreateRoom(uid,data.createData); return;
    }
    //console.logg('playOpt event 274',event);
    if(event==iconst.event.enterRoom)
    {   console.logg('try enter room');
        this.playerEnterRoom(uid,data);
        return;
    }
    if(event==iconst.event.releaseRoom)
    {   this.releaseRoom(uid,data);
        return;
    }
    if(event==iconst.event.query)
    {   this.query(uid,data);
        return;
    }
    if(event==iconst.event.agreeRelease)
    {   this.agreeRelease(uid,data);
        return;
    }
    if(event==iconst.event.startGame)
    {   this.startGame(uid,data);
        return;
    }
    if(event==iconst.event.addBet)
    {
        this.addBet(uid,data);
        return;
    }
    if(event==iconst.event.qiangzhuang)
    {
        this.qiangZhuang(uid,data);
        return;
    }
    if(event==iconst.event.ready2Start)
    {
        this.ready2Start(uid,data);
        return;
    }

    if(event==iconst.event.yaoPai)
    {
        this.yaoPai(uid,data);
        return;
    }
    if(event==iconst.event.tanpai)
    {   this.tanpai(uid,data);
        return;
    }
    if(event==iconst.event.cuopai)
    {   this.cuopai(uid,data);
        return;
    }
    if(event==iconst.event.exitGame)
    {   this.exitGame(uid,data);
        return;
    }
    if(event==iconst.event.userTalk)
    {  this.userTalk(uid,data);
        return;
    }
};

roomManage.prototype.random=function(min,max)
{
    var n=max-min;
    if(n<0) return 0;
    var ret=Math.floor(Math.random()*n)+min;
    return ret;
}

//{owner:uid,roomId:roomInfo.roomId,tick:n,gameType:'10dban'};
roomManage.prototype.playerCreateRoom=function(uid,createData)
{
    var self=this;
    if(!createData)
    {
        console.logg('invalid createData');
        return;
    }
    var status=this.getUserStatus(uid);
    if(status!=iconst.userStatus.onIdle)
    {   console.logg('正在创建中请等待...',status);
        return;
    }
    this.setUserStatus(uid,iconst.userStatus.creating);
    var doAsync= P.coroutine(function*()
    {   var randomId;
        var roomInfo;
        var ret=yield self.tryEnterRoomByHistory(uid);
        if(ret==iconst.loginByHistory)
        {   console.logg('直接从缓存中进入游戏....',uid);
            self.setUserStatus(uid,iconst.userStatus.onIdle);
            return;
        }
        if(ret>0)
        {   self.setUserStatus(uid,iconst.userStatus.onIdle);
            return;
        }
        for(var i=0;i<3;i++)
        {   randomId=self.random(100000,999999);
            roomInfo=yield redis.getHashItem(iconst.gameHistoryName,'room_'+randomId);
            if(roomInfo==null)
            {  break; }
        }
        if(roomInfo!=null)
        {
            console.logg('房间已存在',roomInfo);
            roomInfo=JSON.parse(roomInfo);
            var time=(new Date().getTime()-roomInfo.tick)/1000;
            if(roomInfo.owner!=user.uid)
            {   self.sendByUid(uid,{msg:"创建失败",roomInfo:roomInfo});
                self.setUserStatus(uid,iconst.userStatus.onIdle);
                return;
            }
        }
        console.logg('玩家',uid,'随机创建新房间',randomId);
        var len=self.roomList.length;
        for(var i=0;i<len;i++)
        {
            var rm=self.roomList[i];
            var n=rm.getUserCount();
            if(n==0)
            {
                var rid=rm.createRoom(uid,createData,randomId);
                if(rid>=0)
                {   var userInfo=self.getUserInfo(uid);
                    self.setUserRoom(uid,rid);
                    var n=new Date().getTime();
                    rm.set('createTick',n);
                    roomInfo={owner:uid,rid:rid,serverName:self.serverName,roomId:randomId,
                        roomPsw:randomId,tick:n,gameType:'d89',gameCount:rm.get('gameCount'),
                        innerGameType:createData.gameType,diFeng:createData.diFeng
                    };
                    var s=JSON.stringify(roomInfo);
                    console.logg('玩家',uid,"创建房间",randomId,s);
                    yield self.recordRoom2Redis(rid,s);
                    yield redis.setHashItem('d89_roomMap','r'+randomId,s);
                    yield redis.setHashItem(iconst.gameHistoryName,'room_'+randomId,s);
                }
                break;
            }
        }
        self.setUserStatus(uid,iconst.userStatus.onIdle);
    });
    doAsync().catch(function(e)
    {
        console.logg('create room exception', e.message);
        self.setUserStatus(uid,iconst.userStatus.onIdle);
    });

};

//获取玩家自己开始游戏的所在房间号
roomManage.prototype.getPlayerGamingRoom= P.coroutine(function*(uid)
{
    var key='user_'+uid;
    var  value=yield redis.getHashItem(iconst.gameHistoryName,key);
    if(value)
    {
        var  roomInfo=yield redis.getHashItem(iconst.gameHistoryName,value);
        try{
            var  info=JSON.parse(roomInfo);
            return info;
        }
        catch(e)
        {
            return null;
        }
    }
    return null;
});

roomManage.prototype.playerEnterRoom=function(uid,data)
{
    var self=this;
    var roomPsw=data.roomPsw;
    console.logg('playerEnterRoom 395',data);
    var status=this.getUserStatus(uid);
    if(status!=iconst.userStatus.onIdle)
    {   console.logg('正在进入房间中请等待...',uid,status);
        return;
    }

    self.setUserStatus(uid,iconst.userStatus.entering);
    var doAsync= P.coroutine(function*()
    {
        //console.logg('playerEnterRoom 398');
        var ret=yield self.tryEnterRoomByHistory(uid);
        if(ret==iconst.loginByHistory)
        {   console.logg('直接登录历史房间',uid,'try room',roomPsw);
            self.setUserStatus(uid,iconst.userStatus.onIdle);
            return;
        }
        if(ret==iconst.inOtherGame)
        {
            return;
        }
        roomInfo=yield redis.getHashItem('d89_roomMap','r'+roomPsw);
        //console.logg('playerEnterRoom 400');
        if(roomInfo==null)
        {
            console.logg('房间',roomPsw,'不存在',uid);
            self.sendByUid(uid,{event:iconst.event.error,msg:"房间不存在"});
            self.setUserStatus(uid,iconst.userStatus.onIdle);
            return ;
        }
        var  gamingRoomInfo=yield self.getPlayerGamingRoom(uid);
        var userInfo=self.getUserInfo(uid);
        userInfo.gamingRoomInfo=gamingRoomInfo;
        var roomData=JSON.parse(roomInfo);
        if(!roomData)
        {   console.logg('房间缓存信息解析失败',roomInfo,uid);
            self.sendByUid(uid,{event:iconst.event.error,msg:"房间缓存信息解析失败"});
            self.setUserStatus(uid,iconst.userStatus.onIdle);
            return;
        }
        //console.logg('playerEnterRoom 413');
        var roomId=roomData.rid;
        var rm=self.roomList[roomId];
        if(rm&&rm.getUserCount()>0)
        { var ret=rm.enterRoom(uid,roomPsw);
            if(ret==true)
            {   var userInfo=self.getUserInfo(uid);
                self.setUserRoom(uid,roomId);
            }
            else
            {console.logg('playerEnterRoom failed'); }
        }
        else
        {
            console.logg('can not find room ',uid,roomId);
        }
        self.setUserStatus(uid,iconst.userStatus.onIdle);
    });

    doAsync().catch(function(e)
    {
        self.setUserStatus(uid,iconst.userStatus.onIdle);
       console.logg('playerEnterRoom exception',e);
    });

};


roomManage.prototype.playerExitRoom=function(uid,data)
{

};

roomManage.prototype.playerKeepAlive=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm) { rm.userKeepAlive(uid); return;}
    else { }
};

roomManage.prototype.query=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm) { rm.userQuery(uid,data); return;}
    else { console.logg('invalid room 432',uid);}
};


roomManage.prototype.releaseRoom=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm)
    { rm.releaseRoom(uid,data); return;}
    else
    { console.logg('invalid room 502',uid);
        this.sendByUid(uid,{event:iconst.event.error,msg:'房间不存在'});
    }
};

roomManage.prototype.agreeRelease=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm)
    { rm.agreeRelease(uid,data); return;}
    else
    { console.logg('invalid room 408');}
};

roomManage.prototype.startGame=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm)
    { rm.userStartGame(uid,data); return;}
    else
    { console.logg('invalid room 445');}
};

roomManage.prototype.yaoPai=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm)
    { rm.userYaoPai(uid,data); return;}
    else
    { console.logg('invalid room 453');}
};

roomManage.prototype.addBet=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm)
    { rm.userChooseBet(uid,data); return;}
    else
    { console.logg('invalid room 453');}
};

roomManage.prototype.ready2Start=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm)
    { rm.userReady(uid,data); return;}
    else
    { console.logg('invalid room 453');}
};

roomManage.prototype.qiangZhuang=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm)
    { rm.userQiangzhuang(uid,data); return;}
    else
    { console.logg('invalid room 819');}
};

roomManage.prototype.tanpai=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm)
    { rm.userTanpai(uid,data); return;}
    else
    { console.logg('invalid room 453');}
};

roomManage.prototype.cuopai=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm)
    { rm.userCuopai(uid,data); return;}
    else
    { console.logg('invalid room 888');}
};


roomManage.prototype.exitGame=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm)
    { rm.userExitRoom(uid,data); return;}
    else
    { console.logg('invalid room 573');}
};

roomManage.prototype.userTalk=function(uid,data)
{
    var rm=this.getUserRoom(uid);
    if(rm){ rm.userChat(uid,data); return;}
    else
    { console.logg('invalid room 660');}

};

roomManage.prototype.onUpdate=function()
{
    var len=this.roomList.length;
    for(var i=0;i<len;i++)
    {
        var rm=this.roomList[i];
        var n=rm.getUserCount();
        if(n>0)
        { rm.onUpdate(); }
    }

};


module.exports=roomManage;
